// 创建文章接口
import pool from '@/server/db'
import fs from 'node:fs'
import path from 'node:path'
import { ResultSetHeader } from 'mysql2'

export default defineEventHandler(async event => {
  // 判断用户是否登录
  if (!event.context.userinfo) return r('请登录')
  const { uid } = event.context.userinfo

  // 获取buffer
  const body = await readMultipartFormData(event)

  // 数据校验
  if (!body) return r('请上文件')
  if (!body[0].type?.includes('image')) return r('请上传图片类型的文件')

  // 定义存储的文件名和位置
  const filename = Date.now() + (body[0] as { filename: string }).filename
  const filepath = path.join('public', 'imgs', filename)
  console.log(filepath)

  // 将文件写入public/imgs/目录
  try {
    fs.writeFile(filepath, body[0].data, err => {
      if (err) return r('图片写入失败 ' + err)
    })
  } catch (error) {
    return r('图片写入失败 ' + error)
  }
  // 将头像地址插入用户表（前端默认访问public目录下的文件，所以头像地址去掉public/）
  const avatar = `/imgs/${filename}`
  try {
    const [rows] = await pool.execute(
      'UPDATE `users` SET `avatar` = ? WHERE `id` = ?',
      [avatar, uid]
    )
    if ((rows as ResultSetHeader).affectedRows === 0) {
      return r('头像上传失败')
    }
    return r('上传成功', 1)
  } catch (error) {
    return r('头像上传失败:' + error)
  }
})
